package org.mokusakura.service.impl;

import org.mokusakura.domain.LineItem;
import org.mokusakura.domain.Order;
import org.mokusakura.domain.User;
import org.mokusakura.persistence.mapper.ItemMapper;
import org.mokusakura.persistence.mapper.LineItemMapper;
import org.mokusakura.persistence.mapper.OrderMapper;
import org.mokusakura.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;

/**
 * @author MokuSakura
 */
@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private LineItemMapper lineItemMapper;
    @Autowired
    private ItemMapper itemMapper;

    @Override
    public List<Order> getOrderListByUser(User user) {
        List<Order> orderList = orderMapper.getOrderListByUserId(user.getId());
        orderList.forEach(order -> {
            List<LineItem> lineItemListByOrderId = lineItemMapper.getLineItemListByOrderId(order.getOrderId());
            order.setLineItems(lineItemListByOrderId);
        });
        return orderList;
    }

    @Deprecated
    @Override
    public List<Map<String, String>> getOrderForOrderListPageByUser(User user) {
        List<Map<String, String>> res = null;
        try {
            res = orderMapper.listOrderForOrderListPageByEmail(user.getEmail());
        } catch (SQLException exception) {
            exception.printStackTrace();
        }
        return res;
    }

    @Override
    public Order getOrderByOrderId(Long orderId) {
        Order order = orderMapper.getOrderByOrderId(orderId);
        if (order != null) {
            List<LineItem> lineItemList = lineItemMapper.getLineItemListByOrderId(orderId);
            lineItemList.forEach(lineItem -> {
                lineItem.setItem(itemMapper.getItem(lineItem.getItemId()));
            });
            order.setLineItems(lineItemList);
        }
        return order;
    }

    @Override
    public Integer updateOrder(Order order) {
        return orderMapper.updateOrderStatus(order);
    }
}
